<!-- 修改密码 -->
<template>
    <div class='ChangePassword'>
        <el-form :model="formData" class="demo-ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="账号" prop="username">
                <el-input v-model="formData.username" placeholder="账号"></el-input>
            </el-form-item>
            <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="formData.oldPassword" placeholder="原密码"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="formData.newPassword" placeholder="新密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="Submit">修改</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { updatePassword } from '@/api/parkManage'
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
    const checkUsername = (rule, value, callback) => {
        console.log("value", value)
        if (!value) {
            return callback(new Error('请输入用户名!'))
        } else if (value != this.username) {
            return callback(new Error('请输入当前用户名!'))
        } else {
            callback()
        }
    }
    const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码！'))
        } else if (value.length != 8){
          callback(new Error('新密码必须是8位! '))
        }else if (!/^\w+$/.test(value)){
          callback(new Error('新密码必须字母或数字！'))
        } else {
            callback()
        }
    }
    //这里存放数据
    return {
        formData: {
          username: '',
          oldPassword: '',
          newPassword: ''
        },
        rules: {
          username: [
            { required: true,validator: checkUsername, trigger: 'blur' },
          ],
          oldPassword: [
            { required: true, message: '请输入原密码', trigger: 'blur' }
          ],
          newPassword: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
        },
        username: null,
        userId: null
    };
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    Submit() {
        this.$refs['ruleForm'].validate((valid) => {
            if (valid) {
               console.log('valid success!');
               let dataInfo = { id: this.userId,oldPassword: this.formData.oldPassword,  newPassword: this.formData.newPassword }
               this.$confirm('是否确定修改密码?', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(() => {
                        updatePassword(dataInfo).then(res => {
                            console.log("res", res)
                            this.$message({type: 'success', message: '修改成功!'});
                            setTimeout(() => {
                                this.$store.dispatch('user/logout')
                                this.$router.push(`/login?redirect=${this.$route.fullPath}`)
                            }, 1000)
                            
                        })
                })
               
            } else {
                console.log('error submit!!');
                return false;
            }
        });
    },
    // 获取用户信息
    getUserInfo(){
      this.$store.dispatch('user/getInfo').then(res => {
        console.log('user info', res)
        this.username = res.user.username
        this.userId = res.user.id
      })
    },

},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
    this.getUserInfo()
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.ChangePassword{
    width: 40vh;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    top: 50%;
    padding: 2vh;
    box-shadow: 0px 0px 10px 5px #ccc;
    border-radius: 5px;
    .el-form-item:last-of-type{
        margin: 0 auto;
        text-align: center;
    }
}
.el-input{
    width: 25vh;
}
</style>